package com.buyouchina.web.action.privilege;

import javax.annotation.Resource;
import org.springframework.stereotype.Controller;

import com.buyouchina.bean.privilege.Department;
import com.buyouchina.service.privilege.DepartmentService;
import com.buyouchina.utils.SiteUrl;
import com.buyouchina.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
@Controller("DepartmentManage")
public class DepartmentManageAction extends BaseAction implements ModelDriven<Department>,Preparable{
	private static final long serialVersionUID = 3616545118701361680L;
	@Resource(name="departmentServiceBean") private DepartmentService departmentService;
	private Department department;
	private Integer departmentid; 
	
	public Integer getDepartmentid() {
		return departmentid;
	}
	public void setDepartmentid(Integer departmentid) {
		this.departmentid = departmentid;
	}
	
	public Department getModel() {
		return department;
	}
	public void prepare() throws Exception {
		if(departmentid==null || "".equals(departmentid)){
			department = new Department();
		}else {
			department = departmentService.find(departmentid);
		}
	}
	/*
	 * 添加部门
	 */
	@Permission(model="department",privilegeValue="insert")
	public String addDepartment(){
		if(department.getName() != null && !department.getName().trim().equals("") && !departmentService.exsit(department.getName().trim())){	
			departmentService.save(department);			
			request.setAttribute("message", "部门添加成功");
			request.setAttribute("urladdress", SiteUrl.readUrl("department.list"));
			return "message";
		}else{
			request.setAttribute("message", "部门名已经存在");
		}		
		return "add";
	}
	/*
	 * 修改部门页面
	 */
	@Permission(model="department",privilegeValue="update")
	public String editDepartment(){
		return "edit";
	}
	/*
	 * 更新部门操作
	 */
	@Permission(model="department",privilegeValue="update")
	public String updateDepartment(){
		departmentService.update(department);
		request.setAttribute("message", "信息修改成功");
		request.setAttribute("urladdress", SiteUrl.readUrl("department.list"));
		return "message";
	}
	
	/*
	 * 删除部门
	 */
	@Permission(model="department",privilegeValue="delete")
	public String deleteDepartment(){
		if(departmentService.deleteByDepartment(department)){
			request.setAttribute("message", "删除部门成功！");
			request.setAttribute("urladdress", SiteUrl.readUrl("department.list"));
			return "message";
		}else {
			request.setAttribute("message", "删除部门失败！");
			request.setAttribute("urladdress", SiteUrl.readUrl("department.list"));
			return "message";
		}
		
	}
	/*
	 * 异步判断部门是否存在
	 */
	public String exist(){
		if(departmentService.exsit(department.getName().trim())){
			request.setAttribute("message", "部门名已存在");
		}else {
			request.setAttribute("message", "部门名不存在，可以注册");
		}
		return "usernameIsExsit";
	}
}
